package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;

import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.BookAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.bean.Book;
import com.yzx.lifeassistants.model.IQueryBook;
import com.yzx.lifeassistants.model.callback.IQueryBookCB;
import com.yzx.lifeassistants.model.impl.QueryBookImpl;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 图书检索
 * @author: yzx
 * @time: 2016-3-7 下午1:34:42
 */
public class LibrarySearchActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {
	private ImageButton backBtn;// 返回按钮
	private MaterialEditText contentET;// 搜索内容
	private ImageView searchBtn;// 搜索按钮
	private ListView booksLV;// 图书列表
	private PullToRefreshListView booksPTRLV;// 刷新
	private ILoadingLayout booksILL;// 加载

	private Handler handler;
	private IQueryBookCB queryCallBack;// 回调
	private IQueryBook queryBook;// 查询
	private CircularLoadingDialog dialog;// 加载
	private static final int STATE_REFRESH = 0;// 下拉刷新
	private static final int STATE_MORE = 1;// 加载更多
	private int curPage = 0; // 当前页的编号，从0开始
	private String content;// 搜索内容
	private int loadType;// 加载类型
	private List<Book> dataList;// 图书列表
	private BookAdapter adapter;// 图书列表适配器

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_library_search);
		initView();
		setListener();
		initData();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.library_search_back_btn);
		contentET = (MaterialEditText) findViewById(R.id.library_search_content_et);
		searchBtn = (ImageView) findViewById(R.id.library_search_search_btn);
		booksPTRLV = (PullToRefreshListView) findViewById(R.id.library_search_listview);
		booksILL = booksPTRLV.getLoadingLayoutProxy();
		booksILL.setLastUpdatedLabel("");
		booksILL.setPullLabel("继续拖动");
		booksILL.setRefreshingLabel("正在装载数据···");
		booksILL.setReleaseLabel("放开装载更多");
		booksLV = booksPTRLV.getRefreshableView();
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		searchBtn.setOnClickListener(this);
		// 滑动监听
		booksPTRLV.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem == 0) {
					booksILL.setLastUpdatedLabel("");
					booksILL.setPullLabel("下拉刷新");
					booksILL.setRefreshingLabel("加载中···");
					booksILL.setReleaseLabel("释放刷新");
				} else if (firstVisibleItem + visibleItemCount == totalItemCount) {
					booksILL.setLastUpdatedLabel("");
					booksILL.setPullLabel("继续拖动");
					booksILL.setRefreshingLabel("正在装载数据···");
					booksILL.setReleaseLabel("放开装载更多");
				}
			}
		});
		// 下拉刷新监听
		booksPTRLV.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				if (null == content || "".equals(content)) {
					booksPTRLV.onRefreshComplete();
					showToast("请输入要搜索的内容~", false);
					return;
				}
				// 下拉刷新(从第一页开始装载数据)
				queryBooks(0, STATE_REFRESH);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				if (null == content || "".equals(content)) {
					booksPTRLV.onRefreshComplete();
					showToast("请输入要搜索的内容~", false);
					return;
				}
				// 上拉加载更多(加载下一页数据)
				queryBooks(curPage, STATE_MORE);
			}

		});
		booksLV.setOnItemClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		contentET.setPaddings(DensityUtils.sp2px(this, 32), 0, 0, 0);
		dataList = new ArrayList<Book>();
		adapter = new BookAdapter(this, dataList);
		SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
				adapter);
		swingBottomInAnimationAdapter.setAbsListView(booksLV);
		booksLV.setAdapter(swingBottomInAnimationAdapter);
		handler = new Handler();
		queryCallBack = new IQueryBookCB() {

			@Override
			public void querySuccess(final List<Book> bookList, final int code) {// 查询成功
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						switch (code) {
						case IQueryBookCB.RESULR_NULL: {// 获取结果为空
							if (STATE_MORE == loadType) {
								showToast("暂时还未有更多的书籍信息~", true);
							}
							if (STATE_REFRESH == loadType) {
								showToast("暂时还未有含该关键词的书籍信息~", true);
							}
							break;
						}
						case IQueryBookCB.QUERY_SUCCESS: {// 获取结果不为空
							if (STATE_REFRESH == loadType) {
								dataList.clear();
							}
							dataList.addAll(bookList);
							curPage++;
							break;
						}
						default:
							break;
						}
						booksPTRLV.onRefreshComplete();
						adapter.notifyDataSetChanged();
					}
				});
			}

			@Override
			public void queryError() {// 查询失败
				handler.post(new Runnable() {

					@Override
					public void run() {
						dialog.dismiss();
						showToast("获取失败，请确认网络连接后刷新重试~", false);
						booksPTRLV.onRefreshComplete();
						adapter.notifyDataSetChanged();
					}
				});
			}
		};
		queryBook = new QueryBookImpl(this, queryCallBack);

	}

	/**
	 * 
	 * @Description: 查询图书
	 */
	private void queryBooks(int page, int actionType) {
		loadType = actionType;
		dialog.show();
		queryBook.queryBook(content, page + 1);
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.library_search_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.library_search_search_btn: {// 搜索
			content = contentET.getText().toString().replace(" ", "");
			if ("".equals(content) || null == content) {
				showToast("请输入要搜索的内容~", false);
			} else {
				queryBooks(0, STATE_REFRESH);
			}
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 列表按键监听
	 */
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {

	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.library_search_top_rl);
		} else {
			ToastUtils
					.showAlertToast(this, message, R.id.library_search_top_rl);
		}

	}
}
